#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: comments.py
@contact: zwb15083976291@163.com
@time: 2022/03/01
"""
import time

from common.filters import CommentsArticlesFilter, CommentsChildrenFilter
from common.models import BlogComments
from common.serializers.serializer import CreateCommentsSerializer, CommentsPagingSerializer, CommentsSerializer, \
    CommentsChildPagingSerializer
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.views.views import BasePaginateGenericAPIView


class CommentsManageView(BasePaginateGenericAPIView):
    diff_methods_serializer_class = dict(post=CreateCommentsSerializer,
                                         get=CommentsPagingSerializer
                                         )
    diff_methods_request_params = dict(
        post=dict(required=["email", "name", "content", 'comments_type'],
                  optional=['article_id', 'father_id', 'reply_id']),
        get=dict(required=['comments_type', 'pageNum', 'pageSize'], optional=['article_id'],
                 defualt_value=dict(pageNum=1, pageSize=5)))
    filter_backends = [CommentsArticlesFilter]

    def get(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        # 处理分页数据
        comments = self.filter_queryset(BlogComments.objects.order_by('-create_time'))
        paginator, models = self.paginate_queryset(comments, self.serializer.validated_data)
        serial_fields = ['id', 'father_id', 'reply_id', 'reply_name', 'title_image', 'name', 'is_master', 'content',
                         'comment_like', 'create_time']
        data = CommentsSerializer(instance=models, serial_fields=serial_fields, many=True).data

        article_id = self.serializer.validated_data.get("article_id")
        comments_type = self.serializer.validated_data.get("comments_type")
        count_query_set = BlogComments.objects.filter(comments_type=comments_type)
        if article_id:
            count_query_set = count_query_set.filter(article_id=article_id)

        page_data = self.get_paginated_response(self.serializer.validated_data, paginator, data)
        # 添加子评论信息
        data = self.add_child_comment(data)
        page_data['comments_count'] = count_query_set.count()
        return CommonResponse(data=page_data)

    def add_child_comment(self, data):
        # 添加子评论
        result = []
        for item in data:
            params = dict(pageNum=1, pageSize=5)
            child_comments = BlogComments.objects.filter(father_id=item.get('id')).order_by('-create_time')
            paginator, models = self.paginate_queryset(child_comments, params)
            serial_fields = ['id', 'father_id', 'reply_id', 'reply_name', 'title_image', 'name', 'is_master', 'content',
                             'comment_like', 'create_time']
            child_data = CommentsSerializer(instance=models, serial_fields=serial_fields, many=True).data
            data = self.get_paginated_response(params, paginator, child_data)
            item['children'] = dict(page_info=dict(pageNum=data['pageNum'], total=data['total'],
                                                   totalPages=data['totalPages']), data=data['result'])
            result.append(item)
        return result

    def post(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)
        instance = self.serializer.save()
        serial_fields = ['id', 'father_id', 'reply_id', 'reply_name', 'title_image', 'name', 'is_master', 'content',
                         'comment_like', 'create_time']
        return CommonResponse(data=CommentsSerializer(instance=instance, serial_fields=serial_fields).data)


class ChildrenCommentsView(BasePaginateGenericAPIView):
    diff_methods_serializer_class = dict(get=CommentsChildPagingSerializer)
    diff_methods_request_params = dict(
        get=dict(required=['comments_type', 'pageNum', 'pageSize', 'father_id'],
                 defualt_value=dict(pageNum=1, pageSize=5)))
    filter_backends = [CommentsChildrenFilter]

    def get(self, request):
        ret, msg = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=msg)

        comments = self.filter_queryset(BlogComments.objects.order_by('-create_time'))
        paginator, models = self.paginate_queryset(comments, self.serializer.validated_data)
        serial_fields = ['id', 'father_id', 'reply_id', 'reply_name', 'title_image', 'name', 'is_master', 'content',
                         'comment_like', 'create_time']
        data = CommentsSerializer(instance=models, serial_fields=serial_fields, many=True).data
        return CommonResponse(data=self.get_paginated_response(self.serializer.validated_data, paginator, data))
